package ch.cm.adnroid.cleverlearn.load.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Toast;
import ch.cm.adnroid.cleverlearn.R;
import ch.cm.adnroid.cleverlearn.model.DatabaseManager;

public class CLFileValidator {

    private static final int COUNT_ENDING_LETTERS = 4;
    private static final int AMOUNT_OF_PARTS = 3;
    private static final int START_AMOUNT_OF_RIGHTCOUNTS = 0;
    private static final int MINIMUM_LINECOUNT = 3;

    public boolean validateFile(File file) {
        try {
            String fileEnding = getFileEnding(file);
            if (!fileEnding.equals(".csv")) {
                return false;
            }
            BufferedReader bufferedReader = generatebBufferedReader(file);
            String line = "";
            int lineCount = 0;
            while ((line = bufferedReader.readLine()) != null) {
                lineCount++;
                if (!validateLine(line)) {
                    return false;
                }
            }
            if (lineCount<MINIMUM_LINECOUNT) {
                return false;
            }
            return true;
        } catch (FileNotFoundException e) {
            return false;
        } catch (IOException e) {
            return false;
        }
    }

    private BufferedReader generatebBufferedReader(File file) throws FileNotFoundException {
        FileInputStream fileInputStream = new FileInputStream(file);
        return new BufferedReader(new InputStreamReader(fileInputStream));
    }

    private boolean validateLine(String line) {
        String[] columns = line.split(";");
        boolean parts = columns.length == AMOUNT_OF_PARTS;
        try {
            int b = Integer.parseInt(columns[1]);
            if (!((b==0)|(b==1))) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        
        if (parts) {
            return true;
        }
        return false;
    }

    public void saveInDB(SQLiteDatabase database, File file, Context context) {
        try {
            DatabaseManager databaseManager  = new DatabaseManager(context);
            String tableName = getTableName(file);
            databaseManager.dropTable(database, tableName);
            databaseManager.createTable(database, tableName);
            writeInDB(database, file, tableName);
            Toast.makeText(context, R.string.toast_load_insertquestion, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(context, R.string.toast_load_inserterror, Toast.LENGTH_SHORT).show();
        }
    }


    public void appendInDB(SQLiteDatabase database, File file, Context context) {
        try {
            String tableName = getTableName(file);
            writeInDB(database, file, tableName);
            Toast.makeText(context, R.string.toast_load_insertquestion, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(context, R.string.toast_load_inserterror, Toast.LENGTH_SHORT).show();
        }
    }


    private void writeInDB(SQLiteDatabase database, File file, String tableName) throws Exception {
        try {
            BufferedReader bufferedReader = generatebBufferedReader(file);
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                String firstChar = line.substring(0, 1);
                if (!("#".equals(firstChar))) {

                    String[] values = line.split(";");
                    ContentValues contentValues = new ContentValues();
                    contentValues.put(DatabaseManager.QUESTION_TABLE_COLUMN_QUESTIONTEXT, values[0]);
                    Boolean b = (1 == Integer.parseInt(values[1].trim()));
                    contentValues.put(DatabaseManager.QUESTION_TABLE_COLUMN_YES_NO, b);
                    contentValues.put(DatabaseManager.QUESTION_TABLE_COLUMN_ANSWERTEXT, values[2]);
                    contentValues.put(DatabaseManager.QUESTION_TABLE_COLUMN_RIGHTCOUNT, START_AMOUNT_OF_RIGHTCOUNTS);

                    database.insert(tableName, null, contentValues);
                }
            }
        } catch (FileNotFoundException e) {
            throw new Exception();
        } catch (IOException e) {
            throw new Exception();
        }
    }
    
    
    private String getFileEnding(File file) {
        String fileName = file.getName();
        return file.getName().substring(fileName.length()-COUNT_ENDING_LETTERS,fileName.length());
    }
    
    public String getTableName(File file) {
        return file.getName().substring(0, file.getName().length() - COUNT_ENDING_LETTERS);
    }
}
